package com.tnt.templatemessage.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.itit.itf.okhttp.FastHttpClient;
import io.itit.itf.okhttp.Response;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author zhuangxl
 * @Date 2021-01-15 15:03
 */
public class WechatUtil {


    private static final String APPID = "wx22c16ac0c0f743c6";
    private static final String APPSECRET = "6bde6a1d1a4eb52fe32f983826e154f6";
    private static final String ACCESS_TOKEN_API = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String TEMPLATE_MESSAGE_API = "https://api.weixin.qq.com/cgi-bin/message/template/send";


    /**
     * @Description: 获取 access_token
     * @Author: zhuangxl 
     * @Date: 21/1/15 20:23
     * @return: java.lang.String
     **/
    public static String getAccessionToken() throws Exception{
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("grant_type", "client_credential");
        paramsMap.put("appid", APPID);
        paramsMap.put("secret", APPSECRET);
        Response response = FastHttpClient.get().url(ACCESS_TOKEN_API).addParams(paramsMap).build().execute();
        JSONObject jsonObject = JSONObject.parseObject(response.body().string());
        return jsonObject.get("access_token").toString();

}

    /**
     * @Description:
     * @Author: zhuangxl
     * @Date: 21/1/15 20:25
     * @param access_token: 
     * @param paramsMap: 模板消息对应的参数
     * @return: void
     **/
    public static void sendTemplateMessage(String access_token, Map<String, Object> paramsMap) throws Exception{
        Response response = FastHttpClient.post().url(TEMPLATE_MESSAGE_API+"?access_token="+access_token)
                .addHeader("Accept","application/json")
                .addHeader("Content-Type", "application/json")
                .body(JSON.toJSONString(paramsMap))
                .build().execute();
        System.out.println(response.body().string());
    }
}
